package com.onluy.frameworkcloud.system.interceptor;

import java.io.IOException;  
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.onluy.frameworkcloud.base.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONArray; 
import com.onluy.frameworkcloud.system.annotation.ParamCheck;


public class ParamCheckInterceptor implements HandlerInterceptor {

	protected Logger log = LoggerFactory.getLogger(this.getClass());




	public  void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
		log.info("====================paramCheck postHandle" );
        //super.postHandle(request, response, handler, modelAndView);
	}

	public  void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
		log.info("====================paramCheck afterCompletion" );
//    	 super.afterCompletion(request, response, handler, ex);
	}




	/**
	 * 参数校验器拦截
	 *
	 */

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		log.info("====================paramCheck preHandle start" );

		if(handler instanceof HandlerMethod){
			HandlerMethod method = (HandlerMethod)handler;
	    	//获取方法指定的校验参数注解
			ParamCheck paramCheck = method.getMethodAnnotation(ParamCheck.class);
			log.info("====================  check start" );

			//2、指定需要校验的参数
	    	if(!StringUtils.isEmpty(paramCheck) && paramCheck.value().length > 0 && !"".equals(paramCheck.value()[0])){
	    		String[] paras = paramCheck.value();
	    		StringBuilder errorlist=new  StringBuilder();
				log.info("====================  check for paras start paras:"+ JSON.toJSONString(paras)  );
	    		for (String para : paras) {
	    			String[] ckstr=para.trim().split(":");
	    			String name=ckstr[0];
	    			String text=name;
	    			if(ckstr.length>1) {
	    				text=ckstr[1];
	    			}
	    			String paraValue = request.getParameter(name);
	    			//不能为空
					if(StringUtils.isEmpty(paraValue)){
						errorlist.append(text + "不能为空！");
						errorlist.append(System.getProperty("line.separator"));
					}

				}

				log.info("====================paramCheck errorlist :"+errorlist.toString());
				if(errorlist.length()>0) {
					writerRespInfo(response, false, errorlist.toString());
					return false;
				}

	    	}

			log.info("====================paramCheck end");

	    }
	    return true;
	}

	/**
	 * 向浏览器写返回信息
	 * 
	 * @param response
	 * @param success
	 * @param respDesc
	 * @return
	 * @throws IOException 
	 */
	@SuppressWarnings("unchecked")
	private void writerRespInfo(HttpServletResponse response, Boolean success, String respDesc) throws IOException{
		JsonResult respInfo = new JsonResult();
		respInfo.setSuccess(success);;
		respInfo.setMsg( respDesc);
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write(JSONArray.toJSONString(respInfo));
	}	
}
